package com.jiaoyou.baojian.activity;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.entity.UploadEntity;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class TobeZhuboActivity extends BaseActivity implements View.OnTouchListener {

    @BindView(R.id.record)
    LinearLayout record;
    @BindView(R.id.recorded)
    LinearLayout recorded;
    @BindView(R.id.tips)
    TextView tips;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.sound)
    ImageView sound;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.price)
    EditText price;
    @BindView(R.id.apply)
    Button apply;

    private OptionsPickerView typesPickerView;

    private MediaRecorder mediaRecorder;
    private File audioFile;
    private long startRecord;
    private String audioUrl;
    private boolean isRecorded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ButterKnife.bind(this);

        record.setOnTouchListener(this);
        recorded.setOnTouchListener(this);
    }

    @Override
    public void initData() {
        final List<String> typeList = new ArrayList<>();
        typesPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                type.setText(typeList.get(options1));
            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("类型选择")
                .setSubCalSize(18)
                .setContentTextSize(18)
                .setCyclic(false, false, false)
                .setOutSideCancelable(true)
                .isDialog(false)
                .build();
        typeList.add("少妇");
        typeList.add("人妻");
        typeList.add("熟女");
        typeList.add("御姐");
        typeList.add("萝莉");
        typeList.add("OL");
        typesPickerView.setPicker(typeList);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_tobe_zhubo;
    }

    @OnClick({R.id.type, R.id.apply, R.id.sound, R.id.time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sound:
            case R.id.time:
                playAudio(audioFile);
                break;
            case R.id.type:
                Utils.hideKeyboard(type, this);
                typesPickerView.show();
                break;
            case R.id.apply:
                if(!isRecorded){
                    toast("请先录音");
                    return;
                }
                waiting("音频上传中...");
                Api.getInstance().uploadAudio(audioFile, new BaofangCallback<UploadEntity>(){

                    @Override
                    public void onFailure(Call<BaseResponse<UploadEntity>> call, Throwable t) {
                        toast("上传失败，请重试");
                        stopWaiting();
                    }

                    @Override
                    public void onSuccess(UploadEntity uploadEntity) {
                        stopWaiting();
                        toast("上传成功");
                        audioUrl = uploadEntity.relativePath;

                        apply();
                    }
                });
                break;
        }
    }

    private void apply() {
        if(TextUtils.isEmpty(audioUrl)){
            toast("请提交录音");
            return;
        }
        if(TextUtils.isEmpty(type.getText())){
            toast("请选择类型");
            return;
        }
        if(TextUtils.isEmpty(price.getEditableText().toString())){
            toast("请设置资费");
            return;
        }
        int p;
        try {
            p = Integer.parseInt(price.getEditableText().toString());
        } catch (NumberFormatException e){
            toast("请输入合法的价格");
            return;
        }
        waiting("申请中...");
        Api.getInstance().applyActress(audioUrl, type.getText().toString(), p, new BaofangCallback() {
            @Override
            public void onFailure(Call call, Throwable t) {
                stopWaiting();
                toast("错误：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(Object o) {
                stopWaiting();
                toastFullscreen("申请成功，管理员将在三个工作日内完成审核，请耐心等待");
                onBackPressed();
            }
        });
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                isRecorded = false;
                record.setVisibility(View.VISIBLE);
                recorded.setVisibility(View.INVISIBLE);
                tips.setText("松开结束");
                startRecord = System.currentTimeMillis();
                audioFile = Utils.generalTempFile(".mp3");
                startRecord();
                break;
            case MotionEvent.ACTION_UP:
                tips.setText("请长按此区域录音");
                long time = System.currentTimeMillis() - startRecord;
                this.time.setText(time / 1000 + "秒");
                record.setVisibility(View.INVISIBLE);
                recorded.setVisibility(View.VISIBLE);
                stopRecord();
                if(time < 5 * 1000){
                    toast("录音时间太短，请提供至少5秒的录音");
                    return true;
                }
                if(time > 30 * 1000){
                    toast("录音时间太长，请不要超过30秒");
                    return true;
                }
                isRecorded = true;
                break;
        }
        return true;
    }

    private void startRecord(){
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
        }
        try {
            mediaRecorder.start();
        } catch (IllegalStateException e){
        }
    }

    private void stopRecord(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    mediaRecorder = null;
                } catch (Exception e){}
            }
        }, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        stopPlayAudio();
    }
}
